package com.anji.sp.push.service.impl;

import com.anji.sp.enums.IsDeleteEnum;
import com.anji.sp.enums.RepCodeEnum;
import com.anji.sp.enums.UserStatus;
import com.anji.sp.model.ResponseModel;
import com.anji.sp.model.po.SpApplicationPO;
import com.anji.sp.push.mapper.PushMessageMapper;
import com.anji.sp.push.model.po.PushHistoryPO;
import com.anji.sp.push.model.po.PushMessagePO;
import com.anji.sp.push.model.vo.PushHistoryVO;
import com.anji.sp.push.model.vo.PushMessageHistoryVO;
import com.anji.sp.push.model.vo.PushMessageVO;
import com.anji.sp.push.service.PushHistoryService;
import com.anji.sp.push.service.PushMessageService;
import com.anji.sp.service.SpApplicationService;
import com.anji.sp.util.APPVersionCheckUtil;
import com.anji.sp.util.BeanUtils;
import com.anji.sp.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务推送id记录 服务实现类
 * </p>
 *
 * @author kean
 * @since 2021-01-20
 */
@Service
public class PushMessageServiceImpl extends ServiceImpl<PushMessageMapper, PushMessagePO> implements PushMessageService {

    @Autowired
    private PushMessageMapper pushMessageMapper;
    @Autowired
    private PushHistoryService pushHistoryService;

    @Autowired
    private SpApplicationService applicationService;
    /** 根据数据库必填项，校验是否为空，不校验主键
     * @param pushMessageVO
     * @return
     */
    private ResponseModel validateCreateFieldNotNull(PushMessageVO pushMessageVO){
        if(pushMessageVO == null){
            return RepCodeEnum.NULL_ERROR.parseError("requestModel data");
        }
        /* 该片段由生成器产生，请根据实际情况修改
        if(pushMessageVO.getId() == null){
            return RepCodeEnum.NULL_ERROR.parseError("id");
        }
        if(StringUtils.isBlank(pushMessageVO.getAppKey())){
            return RepCodeEnum.NULL_ERROR.parseError("appKey");
        }
        if(StringUtils.isBlank(pushMessageVO.getMsgId())){
            return RepCodeEnum.NULL_ERROR.parseError("msgId");
        }
        if(StringUtils.isBlank(pushMessageVO.getOperParam())){
            return RepCodeEnum.NULL_ERROR.parseError("operParam");
        }
        if(pushMessageVO.getEnableFlag() == null){
            return RepCodeEnum.NULL_ERROR.parseError("enableFlag");
        }
        if(pushMessageVO.getDeleteFlag() == null){
            return RepCodeEnum.NULL_ERROR.parseError("deleteFlag");
        }
        if(pushMessageVO.getCreateBy() == null){
            return RepCodeEnum.NULL_ERROR.parseError("createBy");
        }
        if(pushMessageVO.getCreateDate() == null){
            return RepCodeEnum.NULL_ERROR.parseError("createDate");
        }
        if(pushMessageVO.getUpdateBy() == null){
            return RepCodeEnum.NULL_ERROR.parseError("updateBy");
        }
        if(pushMessageVO.getUpdateDate() == null){
            return RepCodeEnum.NULL_ERROR.parseError("updateDate");
        }
        if(StringUtils.isBlank(pushMessageVO.getRemarks())){
            return RepCodeEnum.NULL_ERROR.parseError("remarks");
        }
        */
        return ResponseModel.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseModel create(PushMessageVO pushMessageVO) {
        //参数校验
        ResponseModel valid = validateCreateFieldNotNull(pushMessageVO);
        if(valid.isError()){
            return valid;
        }
        //业务校验
        //...todo
        SpApplicationPO spApplicationPO = applicationService.selectByAppKey(pushMessageVO.getAppKey());
        if (Objects.isNull(spApplicationPO)){
            return ResponseModel.errorMsg("appKey不存在");
        }

        //业务处理
        if(pushMessageVO.getEnableFlag()==null){
            pushMessageVO.setEnableFlag(UserStatus.OK.getIntegerCode());
        }
        pushMessageVO.setDeleteFlag(IsDeleteEnum.NOT_DELETE.getIntegerCode());
        pushMessageVO.setUpdateBy(1L);
        pushMessageVO.setCreateDate(LocalDateTime.now());
        pushMessageVO.setUpdateBy(1L);
        pushMessageVO.setUpdateDate(LocalDateTime.now());

        PushMessagePO pushMessagePO = new PushMessagePO();
        BeanUtils.copyProperties(pushMessageVO, pushMessagePO);
        boolean flag = save(pushMessagePO);

        //返回结果
        if(flag){
            return ResponseModel.successData(pushMessagePO);
        }else{
            return ResponseModel.errorMsg(RepCodeEnum.ERROR);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseModel updateById(PushMessageVO pushMessageVO) {
        //参数校验
        if(pushMessageVO == null){
            return RepCodeEnum.NULL_ERROR.parseError("requestModel data");
        }
        Long pushMessageId = pushMessageVO.getId();
        if(pushMessageId == null){
            return RepCodeEnum.NULL_ERROR.parseError("pushMessageId");
        }
        //业务校验
        //...todo

        //业务处理
        PushMessagePO pushMessagePO = getById(pushMessageId);
        if(pushMessagePO == null){
            return RepCodeEnum.NOT_EXIST_ERROR.parseError("pushMessageId="+pushMessageId.longValue());
        }
        pushMessageVO.setUpdateBy(1L);
        pushMessageVO.setUpdateDate(LocalDateTime.now());
        BeanUtils.copyProperties(pushMessageVO, pushMessagePO, true);
        boolean flag = updateById(pushMessagePO);

        //返回结果
        if(flag){
            return ResponseModel.successData(pushMessagePO);
        }else{
            return ResponseModel.errorMsg("修改失败");
        }
    }

    @Override
    public ResponseModel updateByMsgId(PushMessageVO pushMessageVO) {
        //参数校验
        if(pushMessageVO == null){
            return RepCodeEnum.NULL_ERROR.parseError("requestModel data");
        }
        if (StringUtils.isBlank(pushMessageVO.getAppKey())){
            return RepCodeEnum.NULL_ERROR.parseError("appKey");
        }
        if (StringUtils.isBlank(pushMessageVO.getMsgId())){
            return RepCodeEnum.NULL_ERROR.parseError("msgId");
        }
        QueryWrapper<PushMessagePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("app_key", pushMessageVO.getAppKey());
        queryWrapper.eq("msg_id", pushMessageVO.getMsgId());
        PushMessagePO one = getOne(queryWrapper);
        if (Objects.isNull(one)){
            return ResponseModel.errorMsg("查询为空");
        }
        one.setUpdateBy(1L);
        one.setUpdateDate(LocalDateTime.now());
        BeanUtils.copyProperties(pushMessageVO, one, true);
        boolean flag = updateById(one);
        //返回结果
        if(flag){
            return ResponseModel.success();
        }else{
            return ResponseModel.errorMsg("修改失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseModel deleteById(PushMessageVO pushMessageVO) {
        //参数校验
        if(pushMessageVO == null){
            return RepCodeEnum.NULL_ERROR.parseError("requestModel data");
        }
        Long pushMessageId = pushMessageVO.getId();
        if(pushMessageId == null){
            return RepCodeEnum.NULL_ERROR.parseError("pushMessageId");
        }

        //业务处理
        PushMessagePO pushMessagePO = getById(pushMessageId);
        if(pushMessagePO == null){
            return RepCodeEnum.NOT_EXIST_ERROR.parseError("pushMessageId="+pushMessageId.longValue());
        }
        boolean flag = removeById(pushMessageId);

        //返回结果
        if(flag){
            return ResponseModel.successData("删除成功");
        }else{
            return ResponseModel.errorMsg("删除失败");
        }
    }

    @Override
    public ResponseModel queryById(PushMessageVO pushMessageVO) {
        //参数校验
        if(pushMessageVO == null){
            return RepCodeEnum.NULL_ERROR.parseError("requestModel data");
        }
        Long pushMessageId = pushMessageVO.getId();
        if(pushMessageId == null){
            return RepCodeEnum.NULL_ERROR.parseError("pushMessageId");
        }

        //业务处理
        PushMessagePO pushMessagePO = getById(pushMessageId);
        if(pushMessagePO == null){
            return RepCodeEnum.NOT_EXIST_ERROR.parseError("pushMessageId="+pushMessageId.longValue());
        }

        //返回结果
        BeanUtils.copyProperties(pushMessagePO, pushMessageVO);
        return ResponseModel.successData(pushMessageVO);
    }

    @Override
    public ResponseModel queryByPage(PushMessageVO pushMessageVO) {
        //参数校验
        if(pushMessageVO == null){
            return RepCodeEnum.NULL_ERROR.parseError("requestModel data");
        }
        //...todo

        //分页参数
        Page<PushMessageVO> page = new Page<PushMessageVO>(pushMessageVO.getPageNo(), pushMessageVO.getPageSize());
        pushMessageVO.setDeleteFlag(IsDeleteEnum.NOT_DELETE.getIntegerCode());

        //业务处理
        IPage<PushMessageVO> pageList = pushMessageMapper.queryByPage(page, pushMessageVO);

        //返回结果
        return ResponseModel.successData(pageList);
    }

    @Override
    public ResponseModel queryByMsgId(PushMessageVO vo) {
        if (StringUtils.isBlank(vo.getAppKey())){
            return RepCodeEnum.NULL_ERROR.parseError("appKey");
        }
        if (StringUtils.isBlank(vo.getMsgId())){
            return RepCodeEnum.NULL_ERROR.parseError("msgId");
        }
        QueryWrapper<PushMessagePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("app_key", vo.getAppKey());
        queryWrapper.eq("msg_id", vo.getMsgId());
        PushMessagePO one = getOne(queryWrapper);
        if (Objects.nonNull(one)){
            return ResponseModel.successData(one);
        }
        return ResponseModel.errorMsg("未查到数据");
    }

    @Override
    public ResponseModel queryAmountByMsgId(PushMessageVO vo){
        ResponseModel r = queryByMsgId(vo);
        if (r.isError()){
            return r;
        }
        PushMessagePO p = (PushMessagePO) r.getRepData();
        PushHistoryVO pushHistoryVO = new PushHistoryVO();
        pushHistoryVO.setAppKey(p.getAppKey());
        pushHistoryVO.setMsgId(p.getMsgId());
        ResponseModel rH = pushHistoryService.queryByMsgId(pushHistoryVO, 1);
        if (rH.isError()){
            return rH;
        }

        List<PushHistoryPO> pushHistoryPOS= (List<PushHistoryPO>) rH.getRepData();
        if (pushHistoryPOS.size()>0){
            AtomicInteger targetNum = new AtomicInteger(0);
            AtomicInteger successNum = new AtomicInteger(0);
            pushHistoryPOS.stream().map(s -> {
                targetNum.addAndGet(APPVersionCheckUtil.strToInt(s.getTargetNum()));
                successNum.addAndGet(APPVersionCheckUtil.strToInt(s.getSuccessNum()));
                return s;
            }).collect(Collectors.toList());
            p.setTargetNum(targetNum.toString());
            p.setSuccessNum(successNum.toString());
        }
        BeanUtils.copyProperties(p, vo);
        return ResponseModel.successData(vo);
    }


    @Override
    public ResponseModel queryHistoryMsgId(PushMessageVO vo){
        ResponseModel r = queryByMsgId(vo);
        if (r.isError()){
            return r;
        }
        PushMessagePO p = (PushMessagePO) r.getRepData();
        PushHistoryVO pushHistoryVO = new PushHistoryVO();
        pushHistoryVO.setAppKey(p.getAppKey());
        pushHistoryVO.setMsgId(p.getMsgId());
        ResponseModel rH = pushHistoryService.queryByMsgId(pushHistoryVO, 1);
        if (rH.isError()){
            return rH;
        }

        List<PushHistoryPO> pushHistoryPOS= (List<PushHistoryPO>) rH.getRepData();
        PushHistoryPO ph = new PushHistoryPO();
        List detailList = new ArrayList();
        if (pushHistoryPOS.size()>0){
            AtomicInteger targetNum = new AtomicInteger(0);
            AtomicInteger successNum = new AtomicInteger(0);
            pushHistoryPOS.stream().map(s -> {
                targetNum.addAndGet(APPVersionCheckUtil.strToInt(s.getTargetNum()));
                successNum.addAndGet(APPVersionCheckUtil.strToInt(s.getSuccessNum()));
                Map m = new HashMap();
                //1:华为，2:小米，3:oppo，4:vivo，5：极光iOS 6：极光Android
                switch (s.getTargetType()){
                    case "1":
                        m.put("targetName","华为");
                        break;
                    case "2":
                        m.put("targetName","小米");
                        break;
                    case "3":
                        m.put("targetName","oppo");
                        break;
                    case "4":
                        m.put("targetName","vivo");
                        break;
                    case "5":
                        m.put("targetName","极光iOS");
                        break;
                    case "6":
                        m.put("targetName","极光Android");
                        break;
                    default:
                        break;
                }
                m.put("targetNum",s.getTargetNum());
                m.put("successNum",s.getSuccessNum());
                m.put("message",s.getRemarks());
                detailList.add(m);
                BeanUtils.copyProperties(s, ph);
                return s;
            }).collect(Collectors.toList());
            p.setTargetNum(targetNum.toString());
            p.setSuccessNum(successNum.toString());
        }
        PushMessageHistoryVO pushMessageHistoryVO = new PushMessageHistoryVO();
        BeanUtils.copyProperties(p, pushMessageHistoryVO);
        if (pushHistoryPOS.size()>0){
            pushMessageHistoryVO.setDetails(detailList);
            pushMessageHistoryVO.setTitle(ph.getTitle());
            pushMessageHistoryVO.setContent(ph.getContent());
            pushMessageHistoryVO.setExtras(ph.getExtras());
            pushMessageHistoryVO.setIosConfig(ph.getIosConfig());
            pushMessageHistoryVO.setAndroidConfig(ph.getAndroidConfig());
        }
        return ResponseModel.successData(pushMessageHistoryVO);
    }

}
